<template>
  <view class="record-page">
    <view class="header">
      <text class="title">答题记录</text>
    </view>

    <scroll-view
        class="list-container"
        scroll-y="true"
        @scrolltolower="loadMore"
        :refresher-enabled="true"
        :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh"
        :lower-threshold="100"
        enable-back-to-top="true">

      <view v-if="loading && recordList.length === 0" class="loading">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>

      <view v-else-if="recordList.length === 0 && !loading" class="empty">
        <text>暂无答题记录</text>
      </view>

      <view v-else class="record-items">
        <view class="record-items-content">
          <view v-for="(item, index) in recordList"
                :key="index"
                class="record-item"
                :class="{'record-item-hover': item.hover}"
                @tap="viewRecord(item)"
                @touchstart="item.hover = true"
                @touchend="item.hover = false">
            <view class="record-info">
              <text class="question-title">{{ item.questionTitle }}</text>
              <view class="record-meta">
                <view class="tag question-type">{{ getQuestionTypeLabel(item.questionType) }}</view>
                <view class="tag" :class="item.isCorrect ? 'correct' : 'wrong'">
                  {{ item.isCorrect ? '回答正确' : '回答错误' }}
                </view>
              </view>
            </view>
            <view class="record-details">
              <view class="detail-item">
                <text class="detail-label">答题时间</text>
                <text class="detail-value">{{ formatDate(item.answerTime) }}</text>
              </view>
              <view class="detail-item">
                <text class="detail-label">用时</text>
                <text class="detail-value">{{ item.timeSpent }}秒</text>
              </view>
              <view class="detail-item">
                <text class="detail-label">得分</text>
                <text class="detail-value">{{ item.pointsEarned }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 加载更多状态 -->
        <view v-if="loadingMore" class="load-more-loading">
          <view class="loading-spinner small"></view>
          <text>加载更多...</text>
        </view>

        <!-- 没有更多数据 -->
        <view v-if="noMore && recordList.length > 0" class="no-more">
          <text>已加载全部数据</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { listRecord } from "@/api/answerRecord/record";
import { listQuestion } from "@/api/question/question";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { ref } from "vue";
import { getDicts } from "@/api/system/dict/data";
import { getUserProfile } from "@/api/system/user";

const loading = ref(true)
const loadingMore = ref(false)
const refreshing = ref(false)
const noMore = ref(false)
const recordList = ref([])
const questionMap = ref({})
const dict = ref({
  type: {
    question_type: []
  }
})
const userId = ref(null)

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
})

onLoad(() => {
  getDicts("question_type").then(response => {
    dict.value.type.question_type = response.data;
  });

  getUserProfile().then(res => {
    userId.value = Number(res.data.userId)
    queryParams.value.userId = userId.value
    // 先加载题目列表，再加载记录
    loadQuestions()
  })
})

onShow(() => {
  if (userId.value) {
    resetAndReload()
  }
})

// 修复：加载所有题目到内存中，使用合适的查询参数
async function loadQuestions() {
  try {
    // 修复：查询所有启用状态的题目，不限制特定文章
    const response = await listQuestion({
      pageNum: 1,
      pageSize: 10000,
      questionStatus: '1'
      // 移除 generatedTextId 限制，获取所有题目
    })

    const questions = response.rows || response.data || []

    // 构建题目ID到题目信息的映射
    questionMap.value = {}
    questions.forEach(question => {
      questionMap.value[String(question.id)] = question
    })

    console.log('题目加载完成，共', questions.length, '道题目')
    console.log('题目映射:', Object.keys(questionMap.value))

    // 题目加载完成后，再加载记录
    getList()
  } catch (err) {
    console.error('加载题目失败:', err)
    loading.value = false
    uni.showToast({
      title: '加载题目失败',
      icon: 'none'
    })
  }
}

function resetAndReload() {
  queryParams.value.pageNum = 1
  noMore.value = false
  recordList.value = []
  getList()
}

function onRefresh() {
  refreshing.value = true
  // 重新加载题目和记录
  loadQuestions()
  setTimeout(() => {
    refreshing.value = false
  }, 1000)
}

function loadMore() {
  if (loadingMore.value || noMore.value || loading.value) {
    return
  }
  queryParams.value.pageNum++
  getList(true)
}

// 修复：获取答题记录列表，正确匹配题目信息
async function getList(isLoadMore = false) {
  if (isLoadMore) {
    if (loadingMore.value || noMore.value) return;
    loadingMore.value = true;
  } else {
    loading.value = true;
  }

  try {
    const response = await listRecord(queryParams.value);
    const rows = response.rows || response.data || [];
    const total = response.total || 0;

    console.log('获取到答题记录:', rows.length, '条')

    // 处理答题记录数据，匹配题目信息
    const newRecords = rows.map(record => {
      const questionId = String(record.questionId)
      const question = questionMap.value[questionId]

      console.log(`记录ID: ${record.id}, 题目ID: ${questionId}, 找到题目:`, !!question)

      if (question) {
        console.log(`题目标题: ${question.questionTitle}`)
      }

      return {
        ...record,
        questionTitle: question ? question.questionTitle : `未找到题目 (ID: ${questionId})`,
        questionType: question ? question.questionType : '1',
        hover: false
      }
    });

    if (isLoadMore) {
      recordList.value.push(...newRecords);
    } else {
      recordList.value = newRecords;
    }

    const hasMoreData = (queryParams.value.pageNum * queryParams.value.pageSize) < total;
    if (!hasMoreData) {
      noMore.value = true;
    }

  } catch (err) {
    console.error('获取答题记录失败:', err);
    if (isLoadMore) {
      queryParams.value.pageNum--;
    }
    uni.showToast({
      title: '获取答题记录失败',
      icon: 'none'
    });
  } finally {
    if (isLoadMore) {
      loadingMore.value = false;
    } else {
      loading.value = false;
    }
  }
}

function getQuestionTypeLabel(type) {
  const typeDict = dict.value.type.question_type.find(item => item.dictValue === type)
  return typeDict ? typeDict.dictLabel : type
}

function formatDate(dateString) {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

function viewRecord(record) {
  uni.navigateTo({
    url: `/pages/question/answer?id=${record.questionId}&recordId=${record.id}`
  })
}
</script>

<style>
.record-page {
  height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.header {
  padding: 20px 20px 0;
  text-align: center;
  flex-shrink: 0;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8px;
}

.list-container {
  flex: 1;
  height: 100%;
}

.record-items {
  padding: 20px;
  padding-top: 10px;
  min-height: 100%;
}

.record-items-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #999;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty {
  text-align: center;
  padding: 40px;
  color: #999;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.record-item {
  background-color: #fff;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.record-item::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, rgba(24,144,255,0.1), transparent);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.record-item-hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0,0,0,0.1);
}

.record-item-hover::after {
  opacity: 1;
}

.record-info {
  margin-bottom: 15px;
}

.question-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
  display: block;
  line-height: 1.5;
}

.record-meta {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.tag {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.question-type {
  background-color: #e6f7ff;
  color: #1890ff;
  font-weight: 500;
}

.correct {
  background-color: #f6ffed;
  color: #52c41a;
  font-weight: 500;
}

.wrong {
  background-color: #fff2f0;
  color: #ff4d4f;
  font-weight: 500;
}

.record-details {
  display: flex;
  justify-content: space-between;
  padding-top: 15px;
  margin-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.detail-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.detail-label {
  font-size: 12px;
  color: #999;
}

.detail-value {
  font-size: 16px;
  font-weight: 600;
  color: #666;
}

/* 加载更多状态 */
.load-more-loading {
  text-align: center;
  padding: 20px;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  font-size: 14px;
}

.no-more {
  text-align: center;
  padding: 20px;
  color: #ccc;
  font-size: 14px;
}

.loading-spinner.small {
  width: 20px;
  height: 20px;
  border-width: 2px;
}
</style>
